package com.example.demo.projectmanager.controller;

import com.example.demo.projectmanager.entity.Product;
import com.example.demo.projectmanager.entity.User;
import com.example.demo.projectmanager.service.ProductService;
import com.example.demo.projectmanager.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private UserRepository userRepository;

    // 获取所有商品
    @GetMapping("/products")
    public List<Map<String, Object>> getAllProducts() {
        List<Product> list = productService.findAll();
        return list.stream().map(this::toProductMap).collect(java.util.stream.Collectors.toList());
    }

    // 获取单个商品
    @GetMapping("/products/{id}")
    public ResponseEntity<?> getProduct(@PathVariable Long id) {
        Product p = productService.findById(id);
        if (p == null) return ResponseEntity.notFound().build();
        return ResponseEntity.ok(toProductMap(p));
    }

    // 发布商品
    @PostMapping("/products")
    public ResponseEntity<?> publishProduct(
            @RequestParam String title,
            @RequestParam Double price,
            @RequestParam String description,
            @RequestParam(value = "image", required = false) MultipartFile image,
            @AuthenticationPrincipal UserDetails userDetails) throws IOException {
        User seller = userRepository.findByUsername(userDetails.getUsername()).orElse(null);
        if (seller == null) return ResponseEntity.status(401).build();
        Product p = new Product();
        p.setTitle(title);
        p.setPrice(price);
        p.setDescription(description);
        p.setSeller(seller);
        if (image != null && !image.isEmpty()) {
            String url = productService.storeImage(image);
            p.setCoverImage(url);
        }
        productService.save(p);
        return ResponseEntity.ok().build();
    }

    // 删除商品
    @DeleteMapping("/products/{id}")
    public ResponseEntity<?> deleteProduct(@PathVariable Long id, @AuthenticationPrincipal UserDetails userDetails) {
        Product p = productService.findById(id);
        if (p == null) return ResponseEntity.notFound().build();
        if (!p.getSeller().getUsername().equals(userDetails.getUsername())) {
            return ResponseEntity.status(403).body("无权删除");
        }
        productService.deleteById(id);
        return ResponseEntity.ok().build();
    }

    // 获取当前用户发布的商品
    @GetMapping("/users/me/products")
    public List<Map<String, Object>> getMyProducts(@AuthenticationPrincipal UserDetails userDetails) {
        User seller = userRepository.findByUsername(userDetails.getUsername()).orElse(null);
        return productService.findBySeller(seller).stream().map(this::toProductMap).collect(java.util.stream.Collectors.toList());
    }


    // 工具方法：转为前端需要的Map
    private Map<String, Object> toProductMap(Product p) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", p.getId());
        map.put("title", p.getTitle());
        map.put("price", p.getPrice());
        map.put("description", p.getDescription());
        map.put("coverImage", p.getCoverImage());
        map.put("sellerName", p.getSeller() != null ? p.getSeller().getUsername() : "");
        return map;
    }
}
